import {PlusOutlined} from '@ant-design/icons';
import {Button, message, Drawer, FormInstance, Popconfirm, Image} from 'antd';
import React, {useState, useRef} from 'react';
import {PageContainer, FooterToolbar} from '@ant-design/pro-layout';
import type {ProColumns, ActionType} from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  ModalForm,
  ProFormText,
  ProFormSelect,
  ProFormUploadButton,
  ProFormTextArea,
} from '@ant-design/pro-form';
import ProDescriptions, {ProDescriptionsItemProps} from '@ant-design/pro-descriptions';
import {removeData, dataList, addData, updateData, loadData} from './service';
import type {RiskNoticeBody, RiskNoticeListItem, RiskNoticeListPagination} from './data';
import {UploadFile} from 'antd/lib/upload/interface';
import CheckModule from '@/components/CheckModule';

/**
 * 添加节点
 *
 * @param fields
 * @param mode
 */

const handleAdd = async (fields: RiskNoticeBody, mode: boolean) => {
  const hide = message.loading(mode ? '正在保存' : '正在添加');

  try {
    mode ? await updateData({...fields}) : await addData({...fields});
    hide();
    message.success(mode ? '保存成功' : '添加成功');
    return true;
  } catch (error) {
    // hide();
    // message.error(mode ? '保存失败请重试' : '添加失败请重试');
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows: RiskNoticeListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeData(selectedRows.map((row) => row.noticeId));
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const RiskNoticesPage: React.FC = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [currentRow, setCurrentRow] = useState<RiskNoticeListItem>();
  const [selectedRowsState, setSelectedRows] = useState<RiskNoticeListItem[]>([]);

  const columns: ProColumns<RiskNoticeListItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'indexBorder',
      render: (dom, entity, index) => {
        return (
          <span>
            {index +
              1 +
              ((actionRef?.current?.pageInfo?.current || 1) - 1) *
              (actionRef?.current?.pageInfo?.pageSize || 5)}
          </span>
        );
      },
    },
    {
      title: '区域',
      dataIndex: 'region',
    },
    {
      title: '风险等级',
      dataIndex: 'level',
      search: false,
    },
    {
      title: '主要风险有害因素',
      dataIndex: 'reason',
      search: false,
      render: (_, record) => <span style={{whiteSpace: 'pre-wrap'}}>{record?.reason}</span>,
    },
    {
      title: '事故后果',
      dataIndex: 'effect',
      search: false,
      render: (_, record) => <span style={{whiteSpace: 'pre-wrap'}}>{record?.effect}</span>,
    },
    {
      title: '事故预防措施',
      dataIndex: 'preventiveAction',
      search: false,
      render: (_, record) => (
        <span style={{whiteSpace: 'pre-wrap'}}>{record?.preventiveAction}</span>
      ),
    },
    {
      title: '应急救援措施',
      dataIndex: 'rescue_action',
      search: false,
      render: (_, record) => <span style={{whiteSpace: 'pre-wrap'}}>{record?.rescueAction}</span>,
    },
    {
      title: '创建时间',
      sorter: true,
      dataIndex: 'createTime',
      valueType: 'dateTime',
      search: false,
      defaultSortOrder: 'descend',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInDescriptions: true,
      render: (_, record) => [
        <a
          key="view"
          onClick={() => {
            setCurrentRow(record);
            setShowDetail(true);
          }}
        >
          查看
        </a>,
        <a
          key="edit"
          onClick={() => {
            formRef.current?.resetFields();
            setCurrentRow(record);
            setEditMode(true);
            handleModalVisible(true);
          }}
        >
          编辑
        </a>,

        <Popconfirm
          key="delete"
          okButtonProps={{danger: true}}
          title={`确认删除重大风险公告：${record.region}?`}
          onConfirm={async () => {
            setCurrentRow(record);
            await handleRemove([record]);
            actionRef.current?.reloadAndRest?.();
          }}
          okText="删除"
          cancelText="取消"
        >
          <a href="#"> 删除 </a>
        </Popconfirm>,
      ],
    },
  ];

  const [editMode, setEditMode] = useState<boolean>(false);
  const [previewData, setPreviewData] = useState({
    visible: false,
    image: '',
    title: '',
  });

  const uploadProps = {
    headers: {
      Authorization: `Bearer ${localStorage.getItem('token')}`,
    },
    multiple: false,
    // @ts-ignore
    onChange({file}) {
      if (file.status === 'done' && file.response.code !== 200) {
        file.status = 'error';
      }
    },
    onPreview: async (file: UploadFile) => {
      setPreviewData({
        image: file?.response?.data?.url || file.url,
        visible: true,
        title: '查看图片',
      });
    },
    name: 'file',
    listType: 'picture-card',
    max: 1,
  };
  const submitCheckFile = (
    values: RiskNoticeBody,
    fileName: string,
    dataName: string,
    msg: string,
  ) => {
    let file = values[fileName][0];
    if (file.status !== 'done' || (file?.response && file?.response?.code !== 200)) {
      throw new Error(msg);
    }
    values[dataName] = file?.response?.data?.url || file.url;
  };
  return (
    <CheckModule code={'SC'}>
      <PageContainer waterMarkProps={{content: ''}}>
        <ProTable<RiskNoticeListItem, RiskNoticeListPagination>
          headerTitle="重大风险公告列表"
          actionRef={actionRef}
          rowKey="noticeId"
          search={{
            labelWidth: 120,
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                setEditMode(false);
                handleModalVisible(true);
              }}
            >
              <PlusOutlined/> 新建
            </Button>,
          ]}
          request={dataList}
          columns={columns}
          rowSelection={{
            onChange: (_, selectedRows) => {
              setSelectedRows(selectedRows);
            },
          }}
        />
        {selectedRowsState?.length > 0 && (
          <FooterToolbar
            extra={
              <div>
                已选择{' '}
                <a
                  style={{
                    fontWeight: 600,
                  }}
                >
                  {selectedRowsState.length}
                </a>{' '}
                个重大风险公告
              </div>
            }
          >
            <Popconfirm
              key="delete"
              title={`确认删除选中的${selectedRowsState.length}个重大风险公告?`}
              okButtonProps={{danger: true}}
              onConfirm={async () => {
                await handleRemove(selectedRowsState);
                setSelectedRows([]);
                actionRef.current?.reloadAndRest?.();
              }}
              okText="删除"
              cancelText="取消"
            >
              <Button danger>批量删除</Button>
            </Popconfirm>
            {/*<Button type="primary">批量审批</Button>*/}
          </FooterToolbar>
        )}
        <ModalForm<RiskNoticeBody>
          title={currentRow?.noticeId || 0 > 0 ? '编辑重大风险公告' : '新建重大风险公告'}
          formRef={formRef}
          modalProps={{destroyOnClose: true, maskClosable: false}}
          visible={createModalVisible}
          onVisibleChange={(visible) => {
            if (!visible) {
              setCurrentRow(undefined);
            }
            handleModalVisible(visible);
          }}
          onFinish={async (value) => {
            console.log(value);
            try {
              submitCheckFile(value, 'coverFile', 'cover', '图片未上传');
            } catch ({message: msg}) {
              // @ts-ignore
              message.error(msg);
              return;
            }
            const success = await handleAdd(value, editMode);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current?.reload();
              }
            }
          }}
          request={(params) => {
            console.log(params);
            if (params.noticeId > 0) {
              return loadData(params as RiskNoticeBody).then(({data}) => {
                if (data.cover) {
                  data.coverFile = [
                    {
                      url: data.cover,
                      status: 'done',
                    },
                  ];
                }

                return data;
              });
            } else {
              return new Promise<RiskNoticeBody>((resolve) => {
                resolve({
                  noticeId: 0,
                  level: '重大',
                  createTime: '',
                });
              });
            }
          }}
          params={{...currentRow}}
        >
          <ProFormText hidden name="noticeId"/>

          <ProFormText required label={'区域'} name="region"/>
          <ProFormSelect
            name="level"
            required
            label="等级"
            options={[
              {
                label: '重大',
                value: '重大',
              },
            ]}
            fieldProps={{
              optionLabelProp: 'children',
              optionItemRender(item) {
                return <span style={{color: 'red'}}>{item.label}</span>;
              },
            }}
          />
          <ProFormUploadButton
            name="coverFile"
            label="重大风险公告图片"
            required
            max={1}
            // @ts-ignore
            fieldProps={{...uploadProps}}
            action="/v2/enterprise/upload/risk-notice"
          />

          <ProFormTextArea required label={'主要风险有害因素'} name="reason"/>
          <ProFormTextArea required label={'事故后果'} name="effect"/>
          <ProFormTextArea required label={'事故预防措施'} name="preventiveAction"/>
          <ProFormTextArea required label={'应急救援措施'} name="rescueAction"/>
        </ModalForm>

        <Image
          width={200}
          style={{display: 'none'}}
          src={previewData.image}
          preview={{
            visible: previewData.visible,
            src: previewData.image,
            onVisibleChange: (value) => {
              setPreviewData({image: previewData.image, title: '', visible: value});
            },
          }}
        />
        <Drawer
          width={800}
          visible={showDetail}
          onClose={() => {
            setCurrentRow(undefined);
            setShowDetail(false);
          }}
          closable={false}
        >
          {currentRow?.noticeId && (
            <ProDescriptions<RiskNoticeBody>
              column={1}
              bordered={true}
              title={'重大风险公告详情'}
              // @ts-ignore
              request={loadData}
              params={currentRow}
              columns={columns as ProDescriptionsItemProps<RiskNoticeBody>[]}
            />
          )}
        </Drawer>
      </PageContainer>
    </CheckModule>
  );
};

export default RiskNoticesPage;
